package com.yuandengta.yomall.product.service.impl;

import com.yuandengta.common.constant.ProductConstant;
import com.yuandengta.common.to.SkuHasStockTO;
import com.yuandengta.common.to.SpuBoundTO;
import com.yuandengta.common.to.es.SkuEsModel;
import com.yuandengta.common.utils.R;
import com.yuandengta.yomall.product.entity.*;
import com.yuandengta.yomall.product.feign.CouponFeignService;
import com.yuandengta.yomall.product.feign.SearchFeignService;
import com.yuandengta.yomall.product.feign.WareFeignService;
import com.yuandengta.yomall.product.service.*;
import com.yuandengta.yomall.product.vo.BaseAttrs;
import com.yuandengta.yomall.product.vo.Bounds;
import com.yuandengta.yomall.product.vo.Skus;
import com.yuandengta.yomall.product.vo.SpuVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandengta.common.utils.PageUtils;
import com.yuandengta.common.utils.Query;

import com.yuandengta.yomall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 发布商品
     * @param spuVO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuVO spuVO) {
        // 1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        // 2.保存spu的描述图片 pms_spu_info_desc
        List<String> decript = spuVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);

        // 3.保存spu的图片集 pms_spu_images
        List<String> images = spuVO.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 4.保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuVO.getBaseAttrs();
        productAttrValueService.saveProductAttrValue(spuInfoEntity.getId(), baseAttrs);

        // 5.保存spu的积分信息，跨库操作，feign远程调用
        // yomall-sms -> sms_spu_bounds
        Bounds bounds = spuVO.getBounds();
        SpuBoundTO spuBoundTo = new SpuBoundTO();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            // TODO 数据一致性问题：分布式事务解决方案
            log.error("调用远程服务 yomall-coupon 保存积分信息失败");
        }

        // 6.保存spu对应的sku信息
        // sku基本信息 pms_sku_info
        // sku的图片集 pms_sku_images
        // sku的销售属性信息 pms_sku_sale_attr_value
        // sku的满件优惠，满价优惠，会员价等信息，跨库操作
        // yomall-sms -> sms_sku_ladder, sms_sku_full_reduction, sms_member_price
        List<Skus> skus = spuVO.getSkus();
        if (skus != null && skus.size() > 0) {
            skuInfoService.saveSkuInfo(spuInfoEntity, skus);
        }
    }

    /**
     * SPU 检索
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String)params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(wrapper -> {
                wrapper.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String)params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }

        String brandId = (String)params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String catelogId = (String)params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        // 组装数据
        // 查询当前sku的所有可以被用来检索规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.listBaseAttrForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream()
                .map(ProductAttrValueEntity::getAttrId)
                .collect(Collectors.toList());
        // 在指定的属性集合里面，查找出能够被检索的属性
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);

        Set<Long> idSet = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(attr -> {
            return idSet.contains(attr.getAttrId());
        }).map(attr -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(attr, attrs);
            return attrs;
        }).collect(Collectors.toList());

        // 查询出当前spuId对应的所有sku信息
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        // 发送远程调用，库存系统查询是否有库存
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> stockMap = null;
        try {
            List<SkuHasStockTO> tos = wareFeignService.getSkuHasStock(skuIds);
            stockMap = tos.stream().collect(
                    Collectors.toMap(SkuHasStockTO::getSkuId, value -> value.getHasStock()));
        } catch (Exception e) {
            log.error("调用远程库存服务 yomall-ware 查询异常：{}", e);
        }

        // 封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModelList = skus.stream().map(skuInfoEntity -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());

            // 远程调用异常，默认设置有库存
            if (finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            }

            // TODO 热度评分（应该设计为后台可控的复杂操作，热度评分服务）
            skuEsModel.setHotScore(0L);

            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            // 设置检索属性
            skuEsModel.setAttrs(attrsList);

            return skuEsModel;
        }).collect(Collectors.toList());

        // 将数据发送给 ES保存
        R r = searchFeignService.productUp(skuEsModelList);
        if (r.getCode() == 0) {
            // 远程调用成功
            // 更新spu状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // 远程调用失败
            // TODO 重试机制？接口幂等性？
        }
    }

    /**
     * 获取spu信息
     * @param skuId
     * @return
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        SpuInfoEntity spuInfoEntity = getById(skuInfoEntity.getSpuId());
        return spuInfoEntity;
    }

}